package org.database.generator.code.utils;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;

public class FreemarkerUtil {
    private static FreemarkerUtil util;
    private static Configuration cfg;

    private FreemarkerUtil() {

    }

    /**
     * 获取单例对象
     * @param pname ftl模板文件所在路径
     * @return
     */
    public static FreemarkerUtil getInstance(String pname) {
        if (util == null) {
            cfg = new Configuration();
            cfg.setTagSyntax(Configuration.AUTO_DETECT_TAG_SYNTAX);
            cfg.setClassForTemplateLoading(FreemarkerUtil.class, pname);
            util = new FreemarkerUtil();
        }
        return util;
    }


    /**
     * 获取模板对象
     *
     * @param fname 模板文件名称
     * @return
     */
    private Template getTemplate(String fname) {
        try {
            return cfg.getTemplate(fname);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 解析模板到字符串
     * @param root
     * @param fileName
     * @return
     */
    public String process(Map<String, Object> root, String fileName){
        String result = null;
        try {
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            getTemplate(fileName).process(root, new PrintWriter(bos));
            result = new String(bos.toByteArray(), "utf-8");
        } catch (TemplateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }

}  
